package com.znzz.controller;

import com.znzz.entity.Files;
import com.znzz.service.FilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.List;

/**
 * 下载文件控制器
 */

@Controller
@RequestMapping(path = "/download")
public class DownloadController {
    @Autowired
    private FilesService filesService;

    /**
     * 下载某个文件
     *
     * @param id
     */
    @RequestMapping(path = "/downloadFile")
    public void downloadFile(@RequestParam(value = "id") Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException {

        InputStream inputStream;
        BufferedOutputStream outputStream;

        //通过id找到该文件，并得到其文件名
        String fileName = filesService.findFileById(id).getPrefixName();
        String path = request.getSession().getServletContext().getRealPath("/upload") + "\\" + fileName;
        System.out.println("path:" + path);

        //将保存路径作为文件路径
        File file = new File(path);
        //如果文件存在
        if (file.exists()) {
            //得到文件输入流
            inputStream = new BufferedInputStream(new FileInputStream(file));
            //避免中文乱码
            String filename = URLEncoder.encode(fileName, "UTF-8");
            //设置页面不缓存,清空buffer
            response.reset();
            //设置文件下载头
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            //获取文件输出流
            outputStream = new BufferedOutputStream(response.getOutputStream());
            int len;
            while ((len = inputStream.read()) != -1) {
                outputStream.write(len);
                outputStream.flush();
            }
            inputStream.close();
            outputStream.close();

            //下面几行代码其实很垃圾，不能跟数据库同步刷新下载次数，就算加了重定向也无任何作用。无法执行。可以通过切面实现
            Files fileItem = filesService.findFileById(id);
            Long count = fileItem.getDownloadCount() + 1L;
            fileItem.setDownloadCount(count);
            if(filesService.updateDownloadCount(fileItem)){
                response.sendRedirect(request.getContextPath()+"/user/showAllFiles");
            }
        }
    }


    /**
     * 删除某个文件
     *
     * @param id
     * @param response
     * @param request
     * @throws IOException
     * @throws ServletException
     */
    @RequestMapping(path = "/deleteThisFile")
    public void deleteThisFile(@RequestParam(name = "id") Integer id, HttpServletResponse response, HttpServletRequest request) throws IOException, ServletException {
        //先删除本地磁盘存入的文件，不能先删除数据库中的。
        Files files = filesService.findFileById(id);
        System.out.println("files:" + files);
        File file = new File(files.getFileAddress());
        System.out.println("file:" + file);
        if (file.isFile() && file.exists()) {
            if (file.delete()) {
                filesService.deleteById(id);
                response.sendRedirect(request.getContextPath() + "/user/showAllFiles");
                return;
            } else {
                request.getRequestDispatcher("/WEB-INF/pages/deleteFailed.jsp").forward(request, response);
            }
        } else {
            System.out.println("该文件不存在");
            return;
        }
    }

}

